package cn.iocoder.yudao.module.call.controller.admin.notify;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.call.controller.admin.record.vo.CallRecordSaveReqVO;
import cn.iocoder.yudao.module.call.dal.dataobject.record.CallRecordDO;
import cn.iocoder.yudao.module.call.service.notify.CallNotifyService;
import cn.iocoder.yudao.module.call.service.record.CallRecordService;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "呼叫中心 - 话单推送")
@RestController
@RequestMapping("/call/notify")
@Validated
@Slf4j
public class CallNotifyController {


    @Resource
    private CallNotifyService callNotifyService;

    @Resource
    private CallRecordService callRecordService;


    @Resource
    private FileApi fileApi;

    /**
     * 中间号绑定通知
     * @param params
     * @since 2024-07-15
     * @author PetePower
     * @return
     */

    @PostMapping("/bind/{code}")
    @PermitAll
    @OperateLog(enable = false, logArgs = false) //
    public CommonResult<Object> bindNotify(@PathVariable("code") String code, @RequestBody Map<String, String> params) {
        log.info("关系绑定推送： {} -- {}", code, params);
        return success(callNotifyService.handleBind(code, JSONUtil.parseObj(params)));
    }

    @PostMapping("/unbind/{code}")
    @PermitAll
    @OperateLog(enable = false, logArgs = false) //
    public CommonResult<Object> unbindNotify(@PathVariable("code") String code, @RequestBody Map<String, String> params) {
        log.info("关系解绑推送： {} -- {}", code, params);
        return success(callNotifyService.handleUnBind(code, JSONUtil.parseObj(params)));
    }

    @PostMapping("/call-start/{code}")
    @PermitAll
    @OperateLog(enable = false, logArgs = false) //
    public CommonResult<Object> callStartNotify(@PathVariable("code") String code, @RequestBody Map<String, String> params) {
        log.info("通话开始推送： {} -- {}", code, params);
        return success(callNotifyService.handleCallStart(code, JSONUtil.parseObj(params)));
    }

    @PostMapping("/call-end/{code}")
    @PermitAll
    @OperateLog(enable = false, logArgs = false) //
    public CommonResult<Object> callEndNotify(@PathVariable("code") String code, @RequestBody Map<String, String> params) {
        log.info("通话结束推送： {} -- {}", code, params);
        return success(callNotifyService.handleCallEnd(code, JSONUtil.parseObj(params)));
    }

    @PostMapping("/{id}")
    @PermitAll
    @OperateLog(enable = false, logArgs = false) //
    public CommonResult<Object> notify(@PathVariable("id") Long id, @RequestBody Map<String, String> params) {
        return success(callNotifyService.handleRecord(id, JSONUtil.parseObj(params)));
    }

//    @PostMapping("/record/{code}")
//    @PermitAll
//    @OperateLog(enable = false, logArgs = false) //
//    public CommonResult<Object> notify(@PathVariable("code") String code, @RequestBody Map<String, String> params) {
//        log.info("话单回调参数： {} -- {}", code, params);
//        return success(callNotifyService.handleRecord(code, JSONUtil.parseObj(params)));
//    }

    @PostMapping("/record/46d575e2e/{code}")
    @PermitAll
    @TenantIgnore
    @OperateLog(enable = false, logArgs = false) //
    public CommonResult<Object> notify2(@PathVariable("code") String code, @RequestBody String body) {
//        log.info("话单回调参数  ： {} -- {}", code, body);

        return success(callNotifyService.handleRecord(code, JSONUtil.parseObj(body)));
    }


    @PostMapping("/boxUpload")
    @PermitAll
    @OperateLog(enable = false, logArgs = false) // 上传文件，没有记录操作日志的必要
    public CommonResult<String> uploadFile(@RequestParam("recordFile") MultipartFile file, @RequestParam("callId") String callId) throws Exception {
        CallRecordDO recordByUserData = callRecordService.getRecordByUserData(callId);
        if (ObjUtil.isNull(recordByUserData)) {
            return error(100500, "话单不存在");
        }
        String datePath = DateUtil.format(new Date(), "yyyy-MM-dd");
        String path = "/www/wwwroot/scrm.jzsaas.com/record/" + datePath;
        String file1 = fileApi.createFile(file.getOriginalFilename(), path, IoUtil.readBytes(file.getInputStream()));
        String suffix = file1.substring(file1.lastIndexOf("."));
        File file2 = FileUtil.createTempFile(null,suffix,new File("/www/wwwroot/scrm.jzsaas.com/record/" + datePath), true);
        File file3 =  HttpUtil.downloadFileFromUrl(file1, file2, 3600);
        recordByUserData.setTempRecordUrl("" + datePath + file3.getName());
        recordByUserData.setRecordUrl("" + datePath + file3.getName());
        recordByUserData.setDownloadStatus(true);
        callRecordService.updateRecord(BeanUtils.toBean(recordByUserData, CallRecordSaveReqVO.class));
        return success(file1);
    }


    @GetMapping("test")
    @PermitAll
    public CommonResult<String> test() throws FileNotFoundException {
        String templateUrl = "https://scrm-admin.jzsaas.com/admin-api/infra/file/4/get/813a0ecf765db40851c98b019423623fe79b99cf875a05ebb93043b1b23ebaed.mp3";
        String suffix = templateUrl.substring(templateUrl.lastIndexOf("."));
        String datePath = DateUtil.format(new Date(), "yyyy-MM-dd");
        File file = FileUtil.createTempFile(null,suffix,new File("/www/wwwroot/scrm.jzsaas.com/record/" + datePath), true);
        File file2 = HttpUtil.downloadFileFromUrl(templateUrl, file, 3600);
        String filepath = file2.getPath();
        String filename = file2.getName();
        return success(filepath  + "---------" + filename);
    }
}
